import React, { useState, useEffect } from 'react';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts';
import { SyncOutlined } from '@ant-design/icons';
import API from '../../api/client';

// 数据库类型对应的颜色
const DB_TYPE_COLORS = {
    'mysql': '#ff6b6b',
    'postgresql': '#4ecdc4',
    'postgres': '#4ecdc4',
    'oracle': '#ffd166',
    'sqlserver': '#96ceb4',
    'mssql': '#96ceb4',
    'sqlite': '#a0c4ff',
    'mongodb': '#ff9aa2',
    'redis': '#d9b8c4'
  };
  
  // 默认颜色数组（当数据库类型不在预设时使用）
  const DEFAULT_COLORS = [
    '#ff6b6b', '#4ecdc4', '#ffd166', 
    '#96ceb4', '#a0c4ff', '#ff9aa2'
  ];

  const DistributionChart = () => {
    const [chartType, setChartType] = useState('bar');
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(true);
    
    // 获取数据库分布数据
    useEffect(() => {
      const fetchData = async () => {
        setLoading(true);
        try {
          const response = await API.getDbDistribution();
          // console.log("response = "+response)
          const safeResponse = Array.isArray(response) 
          ? response
          : [];
          
          // 转换数据格式并添加颜色
          const formattedData = safeResponse.map(item => ({
            name: item.db_type,
            value: item.cnt,
            color: DB_TYPE_COLORS[item.db_type] || 
                   DEFAULT_COLORS[Math.floor(Math.random() * DEFAULT_COLORS.length)]
          }));
          
          setData(formattedData);
        } catch (error) {
          console.error('获取数据库分布数据失败:', error);
          setData([]);
        } finally {
          setLoading(false);
        }
      };
      
      fetchData();
    }, []);
  
    if (loading) {
      return (
        <div className="card distribution-chart">
          <div className="card-title">
            <h2>数据库任务分布</h2>
          </div>
          <div className="loading-placeholder">
            <SyncOutlined spin style={{ marginRight: 10 }} />
            加载数据库分布数据中...
          </div>
        </div>
      );
    }
  
    if (!data || data.length === 0) {
      return (
        <div className="card distribution-chart">
          <div className="card-title">
            <h2>数据库任务分布</h2>
          </div>
          <div className="empty-state">
            没有可显示的数据库分布数据
          </div>
        </div>
      );
    }
  
    return (
      <div className="card distribution-chart">
        <div className="card-title">
          <h2>数据库任务分布</h2>
          <div className="chart-type-selector">
            <button 
              className={`type-btn ${chartType === 'bar' ? 'active' : ''}`}
              onClick={() => setChartType('bar')}
              style={{
                borderColor: chartType === 'bar' ? 'var(--primary-color)' : '#d9d9d9',
                color: chartType === 'bar' ? 'var(--primary-color)' : '#666',
                background: chartType === 'bar' ? '#e6f7ff' : 'white'
              }}
            >
              柱状图
            </button>
            <button 
              className={`type-btn ${chartType === 'pie' ? 'active' : ''}`}
              onClick={() => setChartType('pie')}
              style={{
                borderColor: chartType === 'pie' ? 'var(--primary-color)' : '#d9d9d9',
                color: chartType === 'pie' ? 'var(--primary-color)' : '#666',
                background: chartType === 'pie' ? '#e6f7ff' : 'white'
              }}
            >
              饼图
            </button>
          </div>
        </div>
        
        <ResponsiveContainer width="100%" height={320}>
          {chartType === 'pie' ? (
            <PieChart>
              <Pie
                data={data}
                cx="50%"
                cy="50%"
                labelLine={true}
                outerRadius={120}
                fill="#8884d8"
                dataKey="value"
                nameKey="name"
                label={({ name, percent }) => `${name}: ${(percent * 100).toFixed(0)}%`}
              >
                {data.map((entry, index) => (
                  <Cell key={`cell-${index}`} fill={entry.color} />
                ))}
              </Pie>
              <Tooltip 
                formatter={(value, name, props) => [`${value} 个任务`, name]}
                contentStyle={{ 
                  backgroundColor: 'white',
                  borderColor: 'var(--primary-color)',
                  borderRadius: '8px'
                }}
              />
            </PieChart>
          ) : (
            <BarChart
              data={data}
              margin={{ top: 20, right: 30, left: 20, bottom: 30 }}
            >
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="name" />
              <YAxis />
              <Tooltip 
                formatter={(value) => [`${value} 个任务`]}
                labelFormatter={(name) => `数据库类型: ${name}`}
                contentStyle={{ 
                  backgroundColor: 'white',
                  borderColor: 'var(--primary-color)',
                  borderRadius: '8px'
                }}
              />
              <Legend 
                formatter={(value) => '任务数量'} 
                payload={[{ value: '任务数量', type: 'square', color: '#8884d8' }]}
              />
              <Bar dataKey="value" name="任务数量">
                {data.map((entry, index) => (
                  <Cell 
                    key={`cell-${index}`} 
                    fill={entry.color}
                    stroke="var(--primary-color)"
                    strokeWidth={1}
                  />
                ))}
              </Bar>
            </BarChart>
          )}
        </ResponsiveContainer>
      </div>
    );
  };
  
  export default DistributionChart;